//
//  EvaluationVc.swift
//  Pods
//
//  Created by eme on 2017/4/5.
//
//

import UIKit
import UtilCore
import CommonCore
import RickonCore

class EvaluationVc: Base_Vc {
    
    /****************************Storyboard UI设置区域****************************/
    
    @IBOutlet weak var submit_Button: UIButton!
    
    @IBOutlet weak var custom_TableView: UITableView!
    
    @IBOutlet weak var pdName_Label: UILabel!
    
    @IBOutlet weak var lineView: UIView!
    
    @IBOutlet weak var button_LineView: UIView!
    /*----------------------------   自定义属性区域    ----------------------------*/
    var OrderDetailsVm:OrderDetailsViewModel?
    
    var orderDetails:OrderDetailsModel?{
        didSet{
            self.custom_TableView.reloadData()
        }
    }
    var imageArr = [[String]]()
    
    var orderID:String?
    
    var cellButtonArr = [UIButton]()                    //按钮数组()
    
    var starButtonArr = [UIButton]()                    //星星数组
    
    var clickedNum = 0                                  //点击星星的位置
    var section = 0                                     //点击星星所属的区
    var pic_Section = 0                                 //点击上传图片
    
    var qiniuVm:Qiniu_Vm?                               //上传图片vm
    
    var textViewArr = [UITextView]()                    //输入框数组
    
    var dataArrForJson = [[String:String]]()            //参数数组
    
    var evaluationVm:SubmitEvaluationVm?                //提交评价Vm
    
    var modelArr = [CustomModel]()
    var numArr = [Int]()
    var textArr = [Int]()
    
    /****************************Storyboard 绑定方法区域****************************/
    
    /**
     星星点击
     */
    @IBAction func stat_Clicked(_ sender: UIButton) {
        
        self.section = (sender.imageView?.tag)!
        self.modelArr[(sender.imageView?.tag)!].statClicked = sender.tag + 1
        self.custom_TableView.reloadData()
        
    }
    /** 
     提交评价按钮
     */
    @IBAction func SubmitEvaluation(_ sender: UIButton) {
        
        sender.isEnabled = false
        for sectionindex in 0...self.orderDetails!.orderDetailsArray.count - 1{
            
            let model = self.orderDetails!.orderDetailsArray[sectionindex]
            
            if modelArr[sectionindex].customText.characters.count > 150{
                textArr.append(0)
            }
            self.numArr.append(self.modelArr[sectionindex].statClicked)
            self.dataArrForJson.append(["detailid":"\(model.detailid)","pdid":"\(model.pdid)","evaluatecommnet":modelArr[sectionindex].customText,"description":"\(self.modelArr[sectionindex].statClicked)","picurl":self.imageArr[sectionindex].joined(separator: ",")])
        }
        
        if numArr.contains(0) == true{
            self.numArr.removeAll()
            self.dataArrForJson.removeAll()
            self.view.toastErrorCode(100054001)
            sender.isEnabled = true
        }else{
            if textArr.contains(0) == true{
                self.textArr.removeAll()
                self.view.toastErrorCode(100054002)
                self.dataArrForJson.removeAll()
                sender.isEnabled = true
            }else{
                self.evaluationVm!.submitevaluation.onNext(JSONHelper.parseToJson(self.dataArrForJson as AnyObject) as String)
            }
            
        }
    }
    
    /**************************** 以下是方法区域 ****************************/
    override func viewDidLoad() {
        super.viewDidLoad()
        self.lineView.backgroundColor = Theme.v.separate_Line
        self.button_LineView.backgroundColor = Theme.v.separate_Line
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.OrderDetailsVm?.iscanevaluate = "1"
        self.OrderDetailsVm?.getOrderDetails.onNext(self.orderID ?? "")
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        
    }
    /**
     界面基础设置
     */
    override func setupUI() {
        /**
         *  自定义 导航栏左侧 返回按钮
         */
        self.customLeftBarButtonItem()
        self.setUpTableView()
        self.setSubmit_Button()

    }
    func setUpTableView(){
        self.custom_TableView.showsVerticalScrollIndicator = false
        custom_TableView.delegate = self
        custom_TableView.dataSource = self
        let view = UIView()
        view.frame = CGRect(x: 0, y: 0, width: 0, height: 7.5)
        custom_TableView.tableHeaderView = view
    }
    
    func deleteImage(_ sender:UIButton){
        //????
        self.imageArr[sender.imageView!.tag].remove(at: sender.tag)
        self.custom_TableView.reloadData()
    }
    func setSubmit_Button(){
        self.submit_Button.titleLabel?.normal_fontSize(15)
        self.submit_Button.layer.masksToBounds = true
        self.submit_Button.layer.cornerRadius = 5
    }
    /**
     绑定到viewmodel 设置
     */
    override func bindToViewModel(){
        
        //-----------------------------------------
        //获取评价商品信息
        
        self.OrderDetailsVm = OrderDetailsViewModel()
        
        self.OrderDetailsVm?.backDate.asObservable().subscribe(onNext:{ data in
            
            self.orderDetails = data
            
            self.pdName_Label.text = data.bdname
            
            for _ in 0...data.orderDetailsArray.count{
                
                self.imageArr.append([String]())
                self.modelArr.append(CustomModel())
            }
            
            
        }).addDisposableTo(disposeBag)
        
        //显示加载动画
        self.OrderDetailsVm?.loading.bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.OrderDetailsVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        //-----------------------------------------
        //上传图片
        
        self.qiniuVm = Qiniu_Vm()
        self.qiniuVm?.uploadImageSuccess.subscribe(onNext:{[unowned self] splicenseurl in
            
            self.imageArr[self.pic_Section].append(splicenseurl)
            
            self.custom_TableView.reloadData()
            
            }).addDisposableTo(disposeBag)
        
        
        self.qiniuVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.qiniuVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
        
        
        //-----------------------------------------
        //提交评价
        self.evaluationVm = SubmitEvaluationVm()
        
        
        self.evaluationVm?.backDate.asObservable().subscribe(onNext:{ data in
            if data == true{
                
                self.dataArrForJson.removeAll()
                self.view.toastCompletion("评论成功", completion: { _ in
                    isrefresh_orderList = true
                    _ = self.navigationController?.popViewController(animated: true)
                })
            }else{
                self.submit_Button.isEnabled = true
            }
            
        }).addDisposableTo(disposeBag)
        
        //显示加载动画
        self.evaluationVm?.loading.asObservable().bindTo(self.view.rx_loading).addDisposableTo(disposeBag)
        
        self.evaluationVm?.error.bindTo(self.view.rx_error).addDisposableTo(disposeBag)
    }
}
extension EvaluationVc:UITableViewDelegate,UITableViewDataSource{
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 4
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        if let model = self.orderDetails{
            return model.orderDetailsArray.count
        }else{
            return 0
        }
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.row == 0{
            let cell = tableView.dequeueReusableCell(withIdentifier: "header") as! EvaluationHeaderTableViewCell
            cell.item = self.orderDetails?.orderDetailsArray[indexPath.section]
            guard #available(iOS 9.0, *) else {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                return cell
            }
            return cell
        }
        else if indexPath.row == 1{
            
            let cell = tableView.dequeueReusableCell(withIdentifier: "describe") as! DescribeTableViewCell
            
            cellButtonArr = [cell.one_Button,cell.two_button,cell.three_Button,cell.four_Button,cell.five_Button]

            
            self.modelArr[indexPath.section].buttonArr = cellButtonArr
            
            /*
             *处理星星变化
             */
            if self.modelArr[indexPath.section].statClicked != 0{
                
                for index in 0...modelArr[indexPath.section].statClicked - 1
                {
                    self.modelArr[indexPath.section].buttonArr[index].setImage(UIImage(named: "shi_Image", in: SansaCore.bundle, compatibleWith: nil), for: .normal)
                }
                
            }else{
                for btn in modelArr[indexPath.section].buttonArr
                {
                    btn.setImage(UIImage(named: "kong_Image", in: SansaCore.bundle, compatibleWith: nil), for: .normal)
                }
            }
            if self.modelArr[indexPath.section].statClicked != 5 && self.modelArr[indexPath.section].statClicked != 0{
                
                for index in self.modelArr[indexPath.section].statClicked ... 4{
                    
                    self.modelArr[indexPath.section].buttonArr[index].setImage(UIImage(named: "kong_Image", in: SansaCore.bundle, compatibleWith: nil), for: .normal)
                }
            }
            
            
            for btn in cellButtonArr{
                
                btn.imageView?.tag = indexPath.section
            }
            guard #available(iOS 9.0, *) else {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                return cell
            }
            return cell
            
        }else if indexPath.row == 2{
            let cell = tableView.dequeueReusableCell(withIdentifier: "tip") as! TipsTableViewCell
            cell.tips_TextView.delegate = self
            cell.tips_TextView.tag = indexPath.section
            
            if modelArr[indexPath.section].customText != ""{
                
                cell.tips_TextView.text = modelArr[indexPath.section].customText
                cell.tips_TextView.textColor = UIColor.black
                
            }else{
                cell.tips_TextView.text = "快来分享你的购买心得!"
                cell.tips_TextView.textColor = UIColor(hex: "c7c7cd")
            }
            
            guard #available(iOS 9.0, *) else {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                return cell
            }
            
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "pic") as! PicTableViewCell
            cell.pic_CollectionView.delegate = self
            cell.pic_CollectionView.dataSource = self
            cell.pic_CollectionView.tag = indexPath.section
            cell.imagekeys = self.imageArr[indexPath.section]
            
            guard #available(iOS 9.0, *) else {
                cell.setNeedsUpdateConstraints()
                cell.updateConstraintsIfNeeded()
                return cell
            }
            return cell
         }
    }
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        switch indexPath.row {
        case 0:
            return 172/2
        case 1:
            return 45
        case 2:
            return 120
        default:
            return (UIScreen.main.bounds.width - 75)/4 + 10
        }
    }
}
